<?php
class PollsController extends PollsAppController {

	var $name = 'Polls';
	var $helpers = array('Html', 'Form');
	
	function beforeFilter(){
		parent::beforeFilter();
		$this->layout = 'administrador';
		
	}
	function index() {
		$this->paginate['order'] = 'Poll.id DESC';
		$this->Poll->recursive = 0;
		$this->set('polls', $this->paginate());
	}

	function view($id = null) {
		if (!$id) {
			$this->Session->setFlash(__('Invalid Poll.', true));
			$this->redirect(array('action'=>'index'));
		}
		$this->set('poll', $this->Poll->read(null, $id));
	}

	function add() {
		if (!empty($this->data)) {
			$this->Poll->create();
			if ($this->Poll->save($this->data)) {
				$poll_id = $this->Poll->getLastInsertId();
				foreach($this->data['PollOption'] as $option){
					if($option['title'] != ''){
						$option['poll_id'] = $poll_id;
						$this->Poll->PollOption->create();
						$this->Poll->PollOption->save($option);	
					}
					
				}
				$this->redirect(array('action'=>'index'));
			} else {
				$this->Session->setFlash(__('The Poll could not be saved. Please, try again.', true));
			}
		}
	}

	function edit($id = null) {
		if (!$id && empty($this->data)) {
			$this->Session->setFlash(__('Invalid Poll', true));
			$this->redirect(array('action'=>'index'));
		}
		if (!empty($this->data)) {
			if ($this->Poll->save($this->data)) {
				$this->Session->setFlash(__('The Poll has been saved', true));
				$this->redirect(array('action'=>'index'));
			} else {
				$this->Session->setFlash(__('The Poll could not be saved. Please, try again.', true));
			}
		}
		if (empty($this->data)) {
			$this->data = $this->Poll->read(null, $id);
		}
	}

	function delete($id = null) {
		if (!$id) {
			$this->Session->setFlash(__('Invalid id for Poll', true));
			$this->redirect(array('action'=>'index'));
		}
		if ($this->Poll->del($id,true)) {
			$this->Session->setFlash(__('Poll deleted', true));
			$this->redirect(array('action'=>'index'));
		}
	}

}
?>